package com.glodon.paas.util;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FileUtil {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(FileUtil.class);
	
	private static String separator = File.separator;
	
	private static final char[] ILLEGAL_CHARACTERS = { '/', '\n', '\r', '\t', '\0', '\f', '`', '?', '*', '\\', '<', '>', '|', '\"', ':' };
	
	//public static final long BLOCK_SIZE=1024*1024*5;
	
	public static boolean isValidatorFileName(String fullName){
		if(StringUtils.isNotEmpty(fullName)){
			char[] cs = fullName.toCharArray();
			for(char c : cs){
				for(char cc:ILLEGAL_CHARACTERS){
					if(cc==c){
						return false;
					}
				}
			}
			return true;
		}
		
		return false;
	}
	
	
	/**
	 * 按顺序将各参数拼接成路劲格式
	 * 如：cat("c:\\aa","bb//","c","filename") ==
	 * c:\aa\bb\c\filename
	 * 
	 * @param path
	 * @return
	 */
	public static String cat(String... paths) {
		String str = "";
		int i = 0;
		// 1 先用分隔符将各子串凭借起来
		for (String path : paths) {
			if (StringUtils.isBlank(path)) {
				continue;
			}
			if (i > 0) {
				str += separator;
			}
			str += path;
			i++;
		}

		// 2 统一分隔符
		if (separator.equals("/")) {
			str = str.replace("\\", separator);
		} else {
			str = str.replace("/", separator);
		}

		// 3 去掉重复的分隔符
		String old = separator + separator;
		while (str.indexOf(old) > -1) {
			str = str.replace(old, separator);
		}

		return str;
	}

	public static String encodeFileName(HttpServletRequest request, String fileName){
			try {
				if(request == null){
					return fileName;
				}
				String agent = request.getHeader("User-Agent");
				if(StringUtils.isEmpty(agent)){
					return fileName;
				}
				else
				//firefox, chrome浏览器
				if (agent.toLowerCase().indexOf("firefox") >=0 || agent.toLowerCase().indexOf("chrome") >=0 ){
					return new String(fileName.getBytes("UTF-8"), "ISO8859-1");
				}
				else {
					return URLEncoder.encode(fileName, "UTF-8");
				}
			} catch (UnsupportedEncodingException e) {
				LOGGER.debug(e.getMessage(), e);
			}
			return fileName;
	}
}
